#include "EchoServer.h"
#include "TcpConnection.h"
#include "KeyRecommander.h"
#include "Dictionary.h"
#include "WebPageQuery.h"
#include "Redis.h"
#include <iostream>
#include <functional>
#include <sstream>

using std::cout;
using std::endl;
using std::bind;
using std::istringstream;

MyTask::MyTask(const string &msg, const TcpConnectionPtr &con,LRU & lru,int flag,MemLRU & memlru)
: _msg(msg)
, _con(con)
,_lru(lru)
,_memlru(memlru)
,flag(flag)
{
}

void MyTask::process()
{   
    if(flag==0){
    KeyRecommander(_msg,_con);
    }else if(flag==1){
    WebPageQuery(_msg,_con,_lru);
    }else{
        _con->sendInLoop("指令错误");
    }
}

EchoServer::EchoServer(size_t threadNum, size_t queSize
                       , const string &ip
                       , unsigned short port)
: _pool(threadNum, queSize)
, _server(ip, port)
,_redisLRU(10)
,_memlru(10)
{

}

EchoServer::~EchoServer()
{

}

//服务器的启动与停止
void EchoServer::start()
{
    _pool.start();

    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&EchoServer::onNewConnection, this, _1)
                           , std::bind(&EchoServer::onMessage, this, _1)
                           , std::bind(&EchoServer::onClose, this, _1));
    _server.start();
}
void EchoServer::stop()
{
    _pool.stop();
    _server.stop();
}

//三个回调函数
void EchoServer::onNewConnection(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has connected!!!" << endl;
}

void EchoServer::onMessage(const TcpConnectionPtr &con)
{
    //解析命令
    string msg = con->receive();
    istringstream iss(msg);
    int flag;
    string content;
    iss>>flag>>content;

    cout << ">>recv msg from client: "  << flag <<" "<< content << endl;
    //接收到客户端的数据之后，可以将数据做业务逻辑的处理
    //将从客户端接受的数据交给线程池进行处理
    MyTask task(content, con,_redisLRU,flag,_memlru);

    _pool.addTask(bind(&MyTask::process, task));

}

void EchoServer::onClose(const TcpConnectionPtr &con)
{
    cout << con->toString() << " has closed!!!" << endl;
}
